package com.tx.admin.security.auth;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.tx.admin.modules.rbac.entity.UserEntity;
import com.tx.admin.security.service.SecurityService;

@Component
public class UserRealm extends AuthorizingRealm {
	
	
	@Autowired
	private SecurityService securityService;

	public UserRealm() {
		super();
		this.setName(this.getClass().getSimpleName());
	}

	@Autowired
	@Override
	public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
		// TODO Auto-generated method stub
		super.setCredentialsMatcher(credentialsMatcher);
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

		System.out.println("权限缓存刷新");
		SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
		this.securityService.getDataFunction().forEach(val -> {
			info.addStringPermission(val.getId());
		});
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String userName=token.getPrincipal().toString();
		UserEntity user=this.securityService.findByUserName(userName);
		
		if(user == null) {
			throw new AuthenticationException("用户不存在");
		}
		
		SimpleAuthenticationInfo  info= new SimpleAuthenticationInfo(user.getUserName(),user.getPassword(),getName());

		return info;
			
	}

	
	
}
